import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    id:  "",
    loginName:  "",
    token: "",
    dict: [],
    canExport: false,
    canDelete: false,
    showLoginDialog: false
  }),

  getters: {
    getDict: (state) => state.dict,
    getLoginName: (state) => state.loginName,
    getCanExport: (state) => state.canExport,
    getCanDelete: (state) => state.canDelete,
  },

  actions: {
    // 初始化用户信息，从localStorage加载
    initUser() {
      // 检查是否在浏览器环境
      if (import.meta.client) {
        const id = localStorage.getItem('userId')
        const loginName = localStorage.getItem('loginName')
        const token = localStorage.getItem('token')
        
        if (id) this.id = id
        if (loginName) this.loginName = loginName
        if (token) this.token = token
      }
    },
    
    updateUser(data) {
      this.id = data.id
      this.loginName = data.loginName
      this.token = data.token
      
      // 同步到 localStorage，仅在客户端执行
      if (import.meta.client) {
        localStorage.setItem('userId', data.id)
        localStorage.setItem('loginName', data.loginName)
        localStorage.setItem('token', data.token)
      }
    },
    
    updateDict(obj) {
      this.dict = obj
    },
    
    updateDictAll(all) {
      this.dict = all
    },
    
    updatePermissions(data) {
      this.canExport = data.canExport
      this.canDelete = data.canDelete
    },

    setShowLoginDialog(show) {
      this.showLoginDialog = show
    },

    // 清除用户信息
    clearUser() {
      this.id = ""
      this.loginName = ""
      this.token = ""
      this.showLoginDialog = false
      
      // 仅在客户端执行
      if (import.meta.client) {
        localStorage.removeItem('userId')
        localStorage.removeItem('loginName')
        localStorage.removeItem('token')
      }
    }
  }
}) 